﻿using System.Collections.Generic;
using ClassMedataBrowser.Domain;
using System.Windows.Forms;
using System.Resources;
using System.Linq;

namespace ClassMetadataBrowser.ToolControls
{
	public class DataGridColumnsManager
	{
		private const string IdColumn = "Id";
		private readonly DataGridView _gridView;
		private readonly ColumnsDescriptor _descriptor;

		public ColumnsDescriptor Descriptor
		{
			get { return _descriptor; }
		}

		public DataGridColumnsManager(DataGridView gridView, ColumnsDescriptor descriptor)
		{
			// temporary check
			if (descriptor == null)
				return;

			_descriptor = descriptor;
			_gridView = gridView;

			if (descriptor.NotSetup)
				SetupDescriptor();
		}

		private void SetupDescriptor()
		{
			foreach (string columnName in GetColumns().Keys)
					_descriptor.ShowColumn(columnName);
		}

		public bool IsVisible(string columnName)
		{
			if (!_descriptor.NotSetup)
				return true;

			return _descriptor.VisibleColumns.Contains(columnName);
		}

		public Dictionary<string, string> GetColumns()
		{
			Dictionary<string, string> columns = new Dictionary<string, string>();
			_gridView.Columns.OfType<DataGridViewColumn>().Where(c => c.HeaderText != IdColumn).ToList().ForEach
				(c => columns.Add(c.Name, c.HeaderText));
			return columns;
		}

		public string GetDescription(string columnName)
		{
			ResourceManager manager = new ResourceManager(typeof(Resources));
			string resource = manager.GetString(columnName);
			if (string.IsNullOrEmpty(resource))
				return "This is a column description";
			return resource;
		}
	}
}
